package cn.itcast.aop;


import cn.itcast.converters.StringToDataConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

@ControllerAdvice
public class InitBinderAdvice {
    //数据类型转换 jsp传出的date 将string转换成date类型  有两种方法
    //第一种
    @Autowired
    private StringToDataConverter stringToDataConverter;
    //初始化数据绑定器1
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder){
        //获取转换服务对象
        ConversionService conversionService = webDataBinder.getConversionService();
        //判断conversionService是否为GenericConversionService类型
        if(conversionService instanceof GenericConversionService){
            //强制类型转换
            GenericConversionService genericConversionService = (GenericConversionService)conversionService;
            //添加类型转换器
            genericConversionService.addConverter(stringToDataConverter);



           // 第二种:
            // webDataBinder.addCustomFormatter(new DateFormatter("yyyy-mm-dd"));
        }
    }
}
